/**
 * 
 */
package zkoran.qrfan;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.os.Environment;

/**
 * Model to access to the storage of matches 
 * 
 * @author zdenda
 * 
 */
public class MatchModel {

	/**
	 * Directory on external storage for application data
	 */
	private static final String DIRECTORY = "/qrFan/";
	
	/**
	 * extension of data files
	 */
	public static final String EXTENSION = ".csv";

	
	/**
	 * private constructor
	 */
	private MatchModel() { }
	
	
	/**
	 * Is external storage available
	 * 
	 * @return TRUE if external storage is available otherwise false
	 */
	public static boolean isAvailable() {
		
		boolean result = false;
		String state = Environment.getExternalStorageState();
		
		// if we can read and write the media
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			result = true;
		}
		
		return result;
		
	}
	
	
	/**
	 * Return app directory on external storage
	 * create it, if it doesn't exist 
	 * 
	 * @return directory
	 */
	private static File getDirectory() {
		
		File directory = new File(Environment.getExternalStorageDirectory().getPath() + DIRECTORY);
		
		if(isAvailable()) {
			
			if (directory.exists() && directory.isDirectory()) {
				return directory;
			} else {
				// create directory if needed
				if(directory.mkdir()) return directory;
			}
			
		}
		
		return null;
	}
	
	
	/**
	 * Return valid name for match from input name
	 * The name can contain only letters, numbers, underscore or hyphen
	 * other characters will be removed
	 * 
	 * @param name input name
	 * @return valid name
	 */
	public static String validName(String name) {
		// remove special chars from name
		return name.replaceAll("[^a-zA-Z0-9_-]", "");
	}
	
	/**
	 * Create new file in app directory which represents match
	 * 
	 * @param name name of the file
	 * @return TRUE if the file was created
	 */
	public static boolean createMatch(String name) {

		boolean result = false;
		String state = Environment.getExternalStorageState();

		// if we can read and write the media
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			
			name = validName(name);
			
			// if name if valid
			if (!name.equals("")) {
				
				File file = getMatchFile(name);

				try {
					
					result = file.createNewFile();
					
				} catch (IOException e) {
					result = false;
				}
				
			}
		}

		return result;

	}
	
	
	/**
	 * Delete file in app directory which represents match
	 * 
	 * @param name match name
	 * @return
	 */
	public static boolean deleteMatch(String name) {
		
		File file = getMatchFile(name);
		
		return file.delete();
		
	}
	
	
	/**
	 * Return all matches in our storage
	 * 
	 * @return all matches
	 */
	public static List<Match> getAllMatches() {
		
		List<Match> matches = new ArrayList<Match>();
		
		File directory = MatchModel.getDirectory();
		
		if(directory != null) {
			
			for (File file : directory.listFiles()) {
				
				String fileName = file.getName();
				
				// only files with file extension EXTENSION
				if (fileName.endsWith(EXTENSION)) {
				    fileName = fileName.substring(0, fileName.length() - EXTENSION.length());
					matches.add(new Match(fileName));
				}
				
			}
			
		}
		
		return matches;
	}

	/**
	 * Add a new fan to match
	 * 
	 * @param name Match name
	 * @param fan Fan identification
	 * @return TRUE if fan was added
	 */
	public static boolean addfan(String name, String fan) {
		
		boolean result = false;
		
		try {
			
			BufferedWriter writer = new BufferedWriter(new FileWriter(getDirectory() + "/" + name + EXTENSION, true));
			writer.append(fan);
			writer.newLine();
			writer.close();
			result = true;
			
			
		} catch (IOException e) {
			result = false;
		}
		
		return result;
		
	}
	
	/**
	 * Returns all fans for chosen match
	 * 
	 * @param match match name
	 * @return list of fans
	 */
	public static List<String> getAllFans(String match) {
		
		List<String> fans = new ArrayList<String>();
		String fan;
		
		try {
			
			BufferedReader reader = new BufferedReader(new FileReader(getDirectory() + "/" + match + EXTENSION));
			
			while ((fan = reader.readLine()) != null) {
				fans.add(fan);
			}
			
		
		} catch (FileNotFoundException e) {
			fans.clear();
		} catch (IOException e) {
			fans.clear();
		}
		
		// reverse, last added fan will be first
		Collections.reverse(fans);
		
		return fans;
		
	}
	
	/**
	 * Update fans for chosen match
	 * 
	 * @param name Match name
	 * @param mFans List of all fans
	 * @return TRUE if fans were added
	 */
	public static boolean updateFans(String name, List<String> mFans) {
		
		boolean result = false;
		
		// reverse, last added fan will be last
		Collections.reverse(mFans);
		
		try {
			
			BufferedWriter writer = new BufferedWriter(new FileWriter(getMatchFile(name)));
			
			for (String fan : mFans) {
				writer.append(fan);
				writer.newLine();
			}
			
			writer.close();
			result = true;
			
			
		} catch (IOException e) {
			result = false;
		}
		
		return result;
		
	}
	
	
	/**
	 * Returns {@link File} which represents match
	 * 
	 * @param name match name
	 * @return
	 */
	private static File getMatchFile(String name) {
		return new File(getDirectory(), name + EXTENSION);
	}

}
